#!/bin/bash

echo "🔧 创建专门解决node-sass问题的Dockerfile..."

# 创建增强版Dockerfile
cat > Dockerfile.node-sass-fix << 'EOF'
# 使用指定的Node.js版本
FROM node:14.21.3-alpine

# 设置工作目录
WORKDIR /app

# 安装系统依赖 (完整解决node-gyp问题)
RUN apk add --no-cache \
    python3 \
    make \
    g++ \
    git \
    libc6-compat \
    linux-headers

# 设置Python环境变量
ENV PYTHON=/usr/bin/python3
ENV PYTHONPATH=/usr/bin/python3

# 配置npm镜像源
RUN npm config set registry https://registry.npmmirror.com/
RUN npm config set sass_binary_site https://npmmirror.com/mirrors/node-sass/
RUN npm config set phantomjs_cdnurl https://npmmirror.com/mirrors/phantomjs/
RUN npm config set electron_mirror https://npmmirror.com/mirrors/electron/

# 设置node-sass环境变量
ENV SASS_BINARY_SITE=https://npmmirror.com/mirrors/node-sass/
ENV NODE_SASS_SKIP_SASS_BINARY_DOWNLOAD_FOR_CI=1
ENV NODE_SASS_FORCE_BINARY=1

# 创建.npmrc文件
RUN echo "registry=https://registry.npmmirror.com/" > .npmrc
RUN echo "sass_binary_site=https://npmmirror.com/mirrors/node-sass/" >> .npmrc
RUN echo "phantomjs_cdnurl=https://npmmirror.com/mirrors/phantomjs/" >> .npmrc
RUN echo "electron_mirror=https://npmmirror.com/mirrors/electron/" >> .npmrc

# 预安装node-sass二进制文件 (多个版本尝试)
RUN npm install -g node-sass@4.14.1 --sass-binary-site=https://npmmirror.com/mirrors/node-sass/ || \
    npm install -g node-sass@4.14.1 --unsafe-perm || \
    npm install -g node-sass@4.14.1 --force || \
    echo "node-sass预安装失败，将在项目安装时重试"

# 复制package文件
COPY package*.json ./

# 安装依赖 (使用多种策略)
RUN npm install --legacy-peer-deps --force --ignore-optional --ignore-engines || \
    npm install --legacy-peer-deps --force --ignore-optional || \
    npm install --legacy-peer-deps --force || \
    npm install --force

# 复制源代码
COPY . .

# 构建项目
RUN echo "开始构建项目..."
RUN npm run build:mp-weixin 2>&1 || (echo "构建失败，显示错误信息" && exit 1)

# 显示构建结果
RUN echo "构建完成，检查输出目录:"
RUN ls -la dist/build/mp-weixin/ 2>/dev/null || echo "mp-weixin目录不存在或为空"

# 保持容器运行
CMD ["tail", "-f", "/dev/null"]
EOF

echo "✅ 创建了增强版Dockerfile: Dockerfile.node-sass-fix"
echo ""
echo "🔧 现在可以测试这个Dockerfile:"
echo "docker build -f Dockerfile.node-sass-fix -t test-node-sass-fix ."
echo ""
echo "或者进入容器测试:"
echo "docker run -it --rm test-node-sass-fix /bin/sh"
